package com.lagouedu.rabbitmq_demo.config;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class RabbitConfig {

    @Bean
    // 声明TTL队列
    public Queue queue(){
        Map<String, Object> props = new HashMap<>();
        // 消息生存时间10s
        props.put("x-message-ttl",10000);
        // 设置该队列关联的死信交换器(当该队列中消息未被消费，则加入死信交换器)
        props.put("x-dead-letter-exchange", "ex.go.dlx");
        // 设置该队列关联的死信交换器的routingKey, 如果没有则使用原队列的routingKey
        props.put("x-dead-letter-routing-key", "key.dlx");

        Queue queue = new Queue("queue.ttl",true,false,false,props);
        return queue;
    }
    //声明死信队列
    @Bean
    public Queue queueDlx(){
        Queue queue = new Queue("queue.dlx",true,false,false,null);
        return queue;
    }

    // 声明ttl交换器
    @Bean
    public Exchange exchange(){
        DirectExchange exchange = new DirectExchange("ex.ttl",true,false,null);
        return exchange;
    }
    //声明死信交换器
    @Bean
    public Exchange exchangeDlx(){
        DirectExchange exchange = new DirectExchange("ex.go.dlx",true,false,null);
        return exchange;
    }

    // ttl交换器与ttl queue
    @Bean
    public Binding binding(){
        return BindingBuilder.bind(queue()).to(exchange()).with("key.ttl").noargs();
    }

    // 绑定死信交换器和死信队列
    @Bean
    public Binding bindingDlx(){
        return BindingBuilder.bind(queueDlx()).to(exchangeDlx()).with("key.dlx").noargs();
    }
}
